<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>种植统计 - 蔬记</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        :root {
            --primary-color: #2ecc71; /* 主色调：绿色（象征种植） */
            --background-color: #f8fff8; /* 页面背景色 - 淡绿色 */
        }
        
        * {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        body {
            background-color: var(--background-color);
        }
        
        /* 底部导航栏 */
        .tab-bar {
            border-top: 1px solid rgba(0, 0, 0, 0.08);
            background-color: white;
        }
        
        .tab-item.active {
            color: var(--primary-color);
            font-weight: 500;
        }
        
        /* 统计卡片样式 */
        .stat-card {
            border-radius: 16px;
            transition: all 0.3s ease;
            border-top: 3px solid var(--primary-color);
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        
        /* 图表容器 */
        .chart-container {
            border-radius: 16px;
            background-color: white;
        }
        
        /* 活动记录项 */
        .activity-item {
            position: relative;
            padding-left: 24px;
        }
        
        .activity-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 6px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: var(--primary-color);
        }
        
        .activity-item:not(:last-child)::after {
            content: '';
            position: absolute;
            left: 5px;
            top: 18px;
            width: 2px;
            height: calc(100% + 8px);
            background-color: #e5e7eb;
        }
        
        /* 骨架屏动画 */
        @keyframes shimmer {
            0% { background-position: -200% 0; }
            100% { background-position: 200% 0; }
        }
        
        .skeleton-loading {
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: shimmer 1.5s infinite;
        }
    </style>
</head>
<body class="min-h-screen pb-20">
    <!-- 页面头部 -->
    <header class="sticky top-0 z-10 bg-white shadow-sm">
        <div class="px-4 py-5">
            <h1 class="text-xl font-bold text-gray-800">种植统计</h1>
            <p class="text-sm text-gray-500">查看你的种植成果和数据分析</p>
        </div>
    </header>

    <!-- 主内容区域 -->
    <main class="px-4 py-5">
        <!-- 主要统计卡片 -->
        <div class="grid grid-cols-2 gap-4 mb-6">
            <div class="stat-card bg-white p-4 shadow-sm">
                <div class="text-gray-500 text-sm mb-1">总种植数</div>
                <div class="flex items-baseline justify-between">
                    <div class="text-2xl font-bold text-gray-800" id="totalPlantsCount">0</div>
                    <div class="text-xs text-green-500 flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span>20%</span>
                    </div>
                </div>
            </div>
            
            <div class="stat-card bg-white p-4 shadow-sm">
                <div class="text-gray-500 text-sm mb-1">活跃种植</div>
                <div class="flex items-baseline justify-between">
                    <div class="text-2xl font-bold text-gray-800" id="activePlantsCount">0</div>
                    <div class="text-xs text-green-500 flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span>15%</span>
                    </div>
                </div>
            </div>
            
            <div class="stat-card bg-white p-4 shadow-sm">
                <div class="text-gray-500 text-sm mb-1">总日志数</div>
                <div class="flex items-baseline justify-between">
                    <div class="text-2xl font-bold text-gray-800" id="totalLogsCount">0</div>
                    <div class="text-xs text-green-500 flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span>30%</span>
                    </div>
                </div>
            </div>
            
            <div class="stat-card bg-white p-4 shadow-sm">
                <div class="text-gray-500 text-sm mb-1">已收获</div>
                <div class="flex items-baseline justify-between">
                    <div class="text-2xl font-bold text-gray-800" id="harvestedPlantsCount">0</div>
                    <div class="text-xs text-green-500 flex items-center">
                        <i class="fa fa-arrow-up mr-1"></i>
                        <span>25%</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 图表区域 -->
        <div class="space-y-6">
            <!-- 操作类型分布图表 -->
            <div class="chart-container p-5 shadow-sm">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">操作类型分布</h3>
                <div class="flex items-center justify-center">
                    <canvas id="operationChart" width="300" height="300"></canvas>
                </div>
            </div>
            
            <!-- 最近种植活动图表 -->
            <div class="chart-container p-5 shadow-sm">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">种植活动时间线</h3>
                <div class="h-64">
                    <canvas id="timelineChart"></canvas>
                </div>
            </div>
            
            <!-- 近期活动记录 -->
            <div class="chart-container p-5 shadow-sm">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">近期活动</h3>
                <div id="activityLog" class="space-y-4 max-h-60 overflow-y-auto">
                    <!-- 活动加载状态 -->
                    <div id="activityLoading" class="py-8 flex flex-col items-center justify-center">
                        <div class="w-10 h-10 border-4 border-green-200 border-t-green-500 rounded-full animate-spin mb-4"></div>
                        <p class="text-sm text-gray-500">加载活动记录中...</p>
                    </div>
                    
                    <!-- 空状态提示 -->
                    <div id="activityEmpty" class="hidden flex flex-col items-center justify-center py-12 text-center">
                        <div class="w-20 h-20 rounded-full bg-green-50 flex items-center justify-center mb-4">
                            <i class="fa fa-calendar-check-o text-3xl text-green-400"></i>
                        </div>
                        <h4 class="text-base font-medium text-gray-800 mb-2">暂无活动记录</h4>
                        <p class="text-sm text-gray-500">开始种植和记录，这里将显示你的种植活动</p>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 底部导航Tab -->
    <nav class="tab-bar fixed bottom-0 left-0 right-0 flex items-center justify-around py-2">
        <a href="home.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-home text-lg"></i>
            <span class="text-xs mt-1">首页</span>
        </a>
        <a href="growing-plants.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-leaf text-lg"></i>
            <span class="text-xs mt-1">菜园</span>
        </a>
        <a href="task.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-tasks text-lg"></i>
            <span class="text-xs mt-1">任务</span>
        </a>
        <a href="stats.html" class="tab-item active flex flex-col items-center py-2 px-3">
            <i class="fa fa-bar-chart text-lg"></i>
            <span class="text-xs mt-1">统计</span>
        </a>
        <a href="profile.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-user text-lg"></i>
            <span class="text-xs mt-1">我的</span>
        </a>
    </nav>

    <script>
        // 页面加载时初始化
        window.addEventListener('load', initStatsPage);
        
        // 初始化统计页面
        function initStatsPage() {
            // 加载数据
            loadStatsData();
            
            // 加载Chart.js库
            loadChartJS().then(() => {
                // 渲染图表
                renderCharts();
            });
        }
        
        // 加载Chart.js库
        function loadChartJS() {
            return new Promise((resolve, reject) => {
                // 检查Chart.js是否已加载
                if (typeof Chart !== 'undefined') {
                    resolve();
                    return;
                }
                
                // 创建script标签
                const script = document.createElement('script');
                script.src = 'https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }
        
        // 加载统计数据
        function loadStatsData() {
            // 从localStorage获取种植数据
            let plantedPlants = JSON.parse(localStorage.getItem('plantedPlants')) || [];
            let plantLogs = JSON.parse(localStorage.getItem('plantLogs')) || [];
            
            // 如果没有数据，使用模拟数据
            if (plantedPlants.length === 0) {
                // 生成模拟种植数据
                plantedPlants = generateMockPlantedPlants();
                localStorage.setItem('plantedPlants', JSON.stringify(plantedPlants));
            }
            
            // 如果没有日志数据，使用模拟数据
            if (plantLogs.length === 0) {
                // 生成模拟日志数据
                plantLogs = generateMockPlantLogs(plantedPlants);
                localStorage.setItem('plantLogs', JSON.stringify(plantLogs));
            }
            
            // 计算统计数据
            const totalPlants = plantedPlants.length;
            const activePlants = plantedPlants.filter(plant => !plant.harvested).length;
            const harvestedPlants = plantedPlants.filter(plant => plant.harvested).length;
            const totalLogs = plantLogs.length;
            
            // 更新UI显示
            document.getElementById('totalPlantsCount').textContent = totalPlants;
            document.getElementById('activePlantsCount').textContent = activePlants;
            document.getElementById('harvestedPlantsCount').textContent = harvestedPlants;
            document.getElementById('totalLogsCount').textContent = totalLogs;
            
            // 显示最近活动记录
            displayRecentActivities(plantLogs);
        }
        
        // 生成模拟种植数据
        function generateMockPlantedPlants() {
            const now = new Date();
            const plants = [
                {
                    id: '1',
                    name: '生菜',
                    type: 'leaf',
                    icon: '🥬',
                    plantedDate: new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString(), // 14天前种植
                    expectedHarvestDate: new Date(now.getTime() + 10 * 24 * 60 * 60 * 1000).toISOString(), // 预计10天后收获
                    harvested: false
                },
                {
                    id: '2',
                    name: '西红柿',
                    type: 'fruit',
                    icon: '🍅',
                    plantedDate: new Date(now.getTime() - 21 * 24 * 60 * 60 * 1000).toISOString(), // 21天前种植
                    expectedHarvestDate: new Date(now.getTime() + 20 * 24 * 60 * 60 * 1000).toISOString(), // 预计20天后收获
                    harvested: false
                },
                {
                    id: '3',
                    name: '胡萝卜',
                    type: 'root',
                    icon: '🥕',
                    plantedDate: new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString(), // 30天前种植
                    expectedHarvestDate: new Date(now.getTime() + 15 * 24 * 60 * 60 * 1000).toISOString(), // 预计15天后收获
                    harvested: false
                },
                {
                    id: '4',
                    name: '青椒',
                    type: 'fruit',
                    icon: '🫑',
                    plantedDate: new Date(now.getTime() - 45 * 24 * 60 * 60 * 1000).toISOString(), // 45天前种植
                    expectedHarvestDate: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000).toISOString(), // 5天前收获
                    harvested: true,
                    harvestDate: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000).toISOString()
                }
            ];
            
            return plants;
        }
        
        // 生成模拟日志数据
        function generateMockPlantLogs(plants) {
            const now = new Date();
            const logs = [];
            const operations = ['water', 'fertilize', 'prune', 'pest', 'note'];
            
            // 为每种植物生成一些日志
            plants.forEach(plant => {
                const plantDate = new Date(plant.plantedDate);
                const daysSincePlanted = Math.floor((now - plantDate) / (1000 * 60 * 60 * 24));
                
                // 根据种植天数生成不同数量的日志
                const logCount = Math.min(10, Math.max(3, Math.floor(daysSincePlanted / 5)));
                
                for (let i = 0; i < logCount; i++) {
                    // 随机选择一个操作类型
                    const operationType = operations[Math.floor(Math.random() * operations.length)];
                    
                    // 随机生成日志日期（在种植日期和当前日期之间）
                    const randomDays = Math.floor(Math.random() * daysSincePlanted);
                    const logDate = new Date(plantDate);
                    logDate.setDate(plantDate.getDate() + randomDays);
                    
                    logs.push({
                        id: `${plant.id}-${operationType}-${Date.now()}-${i}`,
                        plantId: plant.id,
                        plantName: plant.name,
                        plantIcon: plant.icon,
                        operationType: operationType,
                        timestamp: logDate.toISOString(),
                        notes: operationType === 'note' ? getRandomNote() : ''
                    });
                }
                
                // 如果植物已收获，添加收获日志
                if (plant.harvested) {
                    logs.push({
                        id: `${plant.id}-harvest-${Date.now()}`,
                        plantId: plant.id,
                        plantName: plant.name,
                        plantIcon: plant.icon,
                        operationType: 'harvest',
                        timestamp: plant.harvestDate,
                        notes: '植物已收获'
                    });
                }
            });
            
            // 按时间戳排序（最新的在前）
            logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
            
            return logs;
        }
        
        // 获取随机日志内容
        function getRandomNote() {
            const notes = [
                '植物生长状况良好',
                '今天阳光充足，植物生长很快',
                '发现几片黄叶，已清理',
                '浇水后土壤湿润度适宜',
                '施加了适量肥料，希望长得更好'
            ];
            
            return notes[Math.floor(Math.random() * notes.length)];
        }
        
        // 渲染图表
        function renderCharts() {
            // 渲染操作类型分布图表
            renderOperationChart();
            
            // 渲染时间线图表
            renderTimelineChart();
        }
        
        // 渲染操作类型分布图表
        function renderOperationChart() {
            const ctx = document.getElementById('operationChart').getContext('2d');
            
            // 从localStorage获取日志数据
            const plantLogs = JSON.parse(localStorage.getItem('plantLogs')) || [];
            
            // 计算不同操作类型的数量
            const operationCounts = {};
            plantLogs.forEach(log => {
                if (!operationCounts[log.operationType]) {
                    operationCounts[log.operationType] = 0;
                }
                operationCounts[log.operationType]++;
            });
            
            // 准备图表数据
            const labels = [];
            const data = [];
            const backgroundColor = [];
            const operationColors = {
                water: '#3b82f6', // 蓝色 - 浇水
                fertilize: '#22c55e', // 绿色 - 施肥
                prune: '#a855f7', // 紫色 - 修剪
                pest: '#ef4444', // 红色 - 病虫害防治
                note: '#f59e0b', // 橙色 - 笔记
                harvest: '#8b5cf6' // 紫色 - 收获
            };
            
            for (const [type, count] of Object.entries(operationCounts)) {
                labels.push(getOperationTypeName(type));
                data.push(count);
                backgroundColor.push(operationColors[type] || '#6b7280');
            }
            
            // 创建饼图
            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: backgroundColor,
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                pointStyle: 'circle'
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = data.reduce((a, b) => a + b, 0);
                                    const percentage = Math.round((value / total) * 100);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }
        
        // 渲染时间线图表
        function renderTimelineChart() {
            const ctx = document.getElementById('timelineChart').getContext('2d');
            
            // 从localStorage获取日志数据
            const plantLogs = JSON.parse(localStorage.getItem('plantLogs')) || [];
            
            // 按日期分组日志
            const dailyLogs = {};
            const last7Days = getLast7Days();
            
            // 初始化过去7天的数据
            last7Days.forEach(day => {
                dailyLogs[day.date] = 0;
            });
            
            // 统计每天的操作数量
            plantLogs.forEach(log => {
                const logDate = new Date(log.timestamp).toLocaleDateString('zh-CN');
                if (dailyLogs.hasOwnProperty(logDate)) {
                    dailyLogs[logDate]++;
                }
            });
            
            // 准备图表数据
            const labels = last7Days.map(day => day.label);
            const data = last7Days.map(day => dailyLogs[day.date]);
            
            // 创建柱状图
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '每日操作次数',
                        data: data,
                        backgroundColor: 'rgba(46, 204, 113, 0.6)',
                        borderColor: 'rgba(46, 204, 113, 1)',
                        borderWidth: 1,
                        borderRadius: 8,
                        barThickness: 20
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                stepSize: 1
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            padding: 10,
                            cornerRadius: 8,
                            displayColors: false
                        }
                    }
                }
            });
        }
        
        // 获取操作类型的中文名称
        function getOperationTypeName(type) {
            const typeNames = {
                water: '浇水',
                fertilize: '施肥',
                prune: '修剪',
                pest: '病虫害防治',
                note: '记录笔记',
                harvest: '收获'
            };
            
            return typeNames[type] || '其他操作';
        }
        
        // 获取操作类型的图标
        function getOperationTypeIcon(type) {
            const typeIcons = {
                water: 'fa-tint',
                fertilize: 'fa-pagelines',
                prune: 'fa-scissors',
                pest: 'fa-bug',
                note: 'fa-pencil',
                harvest: 'fa-cutlery'
            };
            
            return typeIcons[type] || 'fa-circle';
        }
        
        // 获取操作类型的颜色
        function getOperationTypeColor(type) {
            const typeColors = {
                water: 'text-blue-500',
                fertilize: 'text-green-500',
                prune: 'text-purple-500',
                pest: 'text-red-500',
                note: 'text-orange-500',
                harvest: 'text-purple-600'
            };
            
            return typeColors[type] || 'text-gray-500';
        }
        
        // 获取过去7天的日期
        function getLast7Days() {
            const now = new Date();
            const days = [];
            
            for (let i = 6; i >= 0; i--) {
                const date = new Date(now);
                date.setDate(now.getDate() - i);
                
                days.push({
                    date: date.toLocaleDateString('zh-CN'),
                    label: i === 0 ? '今天' : date.getMonth() + 1 + '/' + date.getDate()
                });
            }
            
            return days;
        }
        
        // 显示最近活动记录
        function displayRecentActivities(plantLogs) {
            const activityLogContainer = document.getElementById('activityLog');
            const activityLoading = document.getElementById('activityLoading');
            const activityEmpty = document.getElementById('activityEmpty');
            
            // 隐藏加载状态
            activityLoading.style.display = 'none';
            
            // 检查是否有活动记录
            if (plantLogs.length === 0) {
                activityEmpty.classList.remove('hidden');
                return;
            }
            
            // 隐藏空状态
            activityEmpty.classList.add('hidden');
            
            // 清空容器
            activityLogContainer.innerHTML = '';
            
            // 获取最近10条活动记录
            const recentActivities = plantLogs.slice(0, 10);
            
            // 添加活动记录项
            recentActivities.forEach(log => {
                const activityItem = document.createElement('div');
                activityItem.className = 'activity-item pb-4';
                
                // 格式化时间
                const formattedTime = formatTime(log.timestamp);
                
                // 获取操作类型信息
                const operationName = getOperationTypeName(log.operationType);
                const operationIcon = getOperationTypeIcon(log.operationType);
                const operationColor = getOperationTypeColor(log.operationType);
                
                // 设置活动项内容
                activityItem.innerHTML = `
                    <div class="flex items-start">
                        <div class="mr-3 mt-1">
                            <i class="fa ${operationIcon} ${operationColor}"></i>
                        </div>
                        <div class="flex-grow">
                            <div class="font-medium text-gray-800 mb-1">
                                ${operationName} - ${log.plantIcon} ${log.plantName}
                            </div>
                            <div class="text-xs text-gray-500 mb-1">
                                ${formattedTime}
                            </div>
                            ${log.notes ? `<div class="text-sm text-gray-600">${log.notes}</div>` : ''}
                        </div>
                    </div>
                `;
                
                // 添加到容器
                activityLogContainer.appendChild(activityItem);
            });
        }
        
        // 格式化时间
        function formatTime(timestamp) {
            const date = new Date(timestamp);
            const now = new Date();
            const diffMs = now - date;
            const diffMins = Math.floor(diffMs / (1000 * 60));
            const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
            const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
            
            if (diffMins < 60) {
                return `${diffMins}分钟前`;
            } else if (diffHours < 24) {
                return `${diffHours}小时前`;
            } else if (diffDays < 7) {
                const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
                return `${weekdays[date.getDay()]} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
            } else {
                return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
            }
        }
    </script>
    
    <!-- 底部导航Tab -->
    <nav class="tab-bar fixed bottom-0 left-0 right-0 flex items-center justify-around py-2 border-t border-gray-200 bg-white">
        <a href="home.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-home text-lg"></i>
            <span class="text-xs mt-1">首页</span>
        </a>
        <a href="growing-plants.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-leaf text-lg"></i>
            <span class="text-xs mt-1">菜园</span>
        </a>
        <a href="task.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-tasks text-lg"></i>
            <span class="text-xs mt-1">任务</span>
        </a>
        <a href="#" class="tab-item flex flex-col items-center py-2 px-3 text-primary font-medium" onclick="return false;">
            <i class="fa fa-bar-chart text-lg"></i>
            <span class="text-xs mt-1">统计</span>
        </a>
        <a href="profile.html" class="tab-item flex flex-col items-center py-2 px-3 text-gray-500">
            <i class="fa fa-user text-lg"></i>
            <span class="text-xs mt-1">我的</span>
        </a>
    </nav>
</body>
</html>